const app = getApp()
const util = require('../../../utils/util.js')
const bookmark_set = require('../utils/bookmark_set.js')
const swipe_page = require('../ti_do/swipe_page')
const {domainName, oss_domain} = app.globalData
const header= { 'AUTHORIZATION':'JWT ' + wx.getStorageSync('token')}

// 判卷
const grade_paper=(that)=>{
  let array = that.data.ti_list
  const result = array.reduce((acc,  item) => {
    if (item.result === 1) acc.correct++; 
    if (item.result === 2) {
      acc.wrong++;
      acc.wrongs.push({question_id:item.id, selected_id:item.select, read_at:item.start_read_time, select_at:item.select_time});
    }; 
    if (item.select) {
      acc.finished++; 
      acc.finished_questions.push({question:item.id, selected:item.select, read_at:item.start_read_time, select_at:item.select_time, result:item.result, chapter:item.chapter.code, section:item.section})
    }; 
    return acc;
    // 完成数量、正确数量、错误数量、错误习题、阅读时间、选择时间、是否正确。
  }, {finished: 0, correct: 0, wrong: 0, wrongs:[],finished_questions:[]});
  return result
}

// 加载题目
const load_questions=(that)=>{
    // var sections = that.data.test_paper_info.sections.map(section => section.id);
    wx.request({
    url: domainName + 'questions/paper/questions/list',
    data: {
      sections:that.data.test_paper_info.sections,
      capacity:that.data.test_paper_info.capacity,
      is_shuffle_questions:that.data.test_paper_info.is_shuffle_questions,
      is_shuffle_options:that.data.test_paper_info.is_shuffle_options,
    },
    header:header,
    method:'get',
    success: res => {
      wx.hideLoading()
      console.log('res.data',res)
      if(res.data.result==1){
        let ti_list = res.data.data
        var list_show = ti_list.slice(0,3)
        that.setData({
            ti_list:ti_list,
            list_show:list_show,
            start_read_time:util.formatTime(new Date()),  // 记录开始读题时间
        })
        that.data.start_time = util.formatTime(new Date())
        count_down(that, that.data.test_paper_info.duration)
      }else{
        let content = res.data.detail
        wx.showModal({
          content: content,
          showCancel: false,
          title: '提示！',
        })
      }
    },
  })
}
// 加载收藏夹
const load_bookmarks=(that)=>{
  wx.request({
    url: domainName + 'questions/bookmark/questionIds',
    data: {},
    header: {
      'content-type':'application/x-www-form-urlencoded',
      'AUTHORIZATION':'JWT ' + wx.getStorageSync('token'),
    },
    method:'GET',
    success: res => {
      wx.hideLoading()
      console.log('res',res)
      if(res.data.result==1){
        that.setData({
          ti_bookmarks:res.data.data.bookmarks,
          student:res.data.data.student,
        })
      }
    },
  })
}
// 倒计时
const count_down=(that,test_duration)=>{
  var timer_id = setInterval(() => {
    if(that.data.count_down>0){
      that.setData({
        count_down:that.data.count_down - 1,
      })    
    }else{
      clearInterval(that.data.timer_id)
      let showText = '时间到！已经自动提交试卷！'
      submit(that, showText)
    }
  }, 1000);
  that.setData({
    timer_id:timer_id,
    count_down:test_duration,
  })
}
  
// 提交打分
const submit_opt=(that)=>{
  let unfinished = that.data.ti_list.length - that.data.finished
  if(!this.data.userInfo.relative_jgs.student_jg?.student){
    wx.showModal({
      content: '仅正式学员有此权限！',
      showCancel: false,
      title: '提示',
    })
  }else if(!that.data.test_paper_info){
    wx.showModal({
      content: '抱歉，未检测到试卷，请联系客服',
      showCancel: false,
      title: '提示',
    })
  }else if(unfinished>0){
    wx.showModal({
      content: '未做 ' + unfinished + ' 题，确定提交吗？',
      title: '提醒',
      success: res => {
        if(res.confirm){
          submit(that)
        }
      },
    })
  }else{
    wx.showModal({
      content: '确定要提交吗？',
      showCancel: true,
      title: '提示',
      success: res => {
        if(res.confirm){
          submit(that)
        }
      },
    })
  }
}

// 提交
const submit=(that, showText)=>{
  var transcript = grade_paper(that)
  wx.showLoading({
    title: '大量数据上传中……',
    mask:true,
  })
  var submit_time = new Date()
  // “~~”=取整数部分
  var cost = ~~(Math.abs(new Date(submit_time).getTime() - new Date(that.data.start_time).getTime())/1000)
  var formData = {
    test_paper:that.data.test_paper_info.id,
    // 应该使用实际题量（因为可能后端不够设置的题量）
    capacity:that.data.ti_list.length,
    test_type:that.data.test_paper_info.id?'uniform':'self',
    student:this.data.userInfo.relative_jgs.student_jg?.student,
    start_time:that.data.start_time,
    submit_time:util.formatTime(submit_time),
    cost:cost,
    finished: transcript.finished,
    correct: transcript.correct,
    wrong: transcript.wrong,
    finished_questions: transcript.finished_questions,
  }
  wx.request({
    url: domainName + 'questions/transcript/create',
    data: formData,
    method:'POST',    
    header:header,
    success: res => {
      wx.hideLoading()
      console.log('res', res)
      const res_data = res.data
      if(res.data.result==1){
        clearInterval(that.data.timer_id)
        wx.showModal({
          content: showText || '提交完成！',
          showCancel: false,
          title: '提示',
          success: res => {
            wx.reLaunch({
              url: '/pages/questions/transcript_detail/transcript_detail?transcript=' + encodeURIComponent(JSON.stringify({
                wrongs:transcript.wrongs, ...res_data.data
              })),
            })
          },
        })
      }else{
        let content = res.data.data.detail
        wx.showModal({
          content: content,
          showCancel: false,
          title: '提示！',
        })
      }
    },
    fail:err=>{
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  })

}

const count_finished = (list) => {
  var finished = 0
  for(var i=0;i<list.length;i++){
    if(list[i].select && list[i].result){
      finished += 1
    }
  }
  return finished
}

// 开始选择
const sel=(that,e)=>{
  // console.log('开始选择')
  // let select = e.currentTarget.id
  let index1 = e.currentTarget.id
  console.log('index1',index1)
  let index = e.currentTarget.dataset.index
  let list_show = that.data.list_show
  // 对比答案，并写入结果
  if(list_show[index].options[index1].is_correct){
    var result = 1  // 正确
  }else{
    var result = 2  // 错误
  }
  // 将所选答案写入
  list_show[index].select= list_show[index].options[index1].id
  list_show[index].result= result
  list_show[index].start_read_time= that.data.start_read_time
  list_show[index].select_time= util.formatTime(new Date())
  // 计算已做习题题量
  let finished = count_finished(that.data.ti_list)
  that.setData({
    list_show:list_show,
    ti_list:that.data.ti_list,
    finished:finished,
  })

}
// 查看答题卡
const open_drawer=(that)=>{that.setData({view_card:true})}
//关闭答题卡
const close_drawer=(that)=>{that.setData({view_card:false})}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ti_bookmarks : [],
    ti_list : [{ti_id:null}],
    icon_url:oss_domain + 'static/picture/app_icon/',
    view_card:false,
    count_down:600, // 默认时间600秒
    finished:0,
    current_list_index:0,
    last_current_index:0,
  },

  // 滑动swiper事件
  swiperchange(e){
    // console.log('滑动swiper事件',e)
    swipe_page.swiperchange(this, e)
  },
  // 前往习题
  go_ti(e){
    let index = parseInt(e.currentTarget.id)
    swipe_page.go_ti_perform(this, index)
  },
  // 查看答题卡
  open_drawer(){open_drawer(this)},
  //关闭答题卡
  close_drawer(){close_drawer(this)},

  // 提交询问
  submit_opt(e){app.get_vibration();submit_opt(this,e)},
 
  // 收藏习题
  set_bookmark(e){app.get_vibration();
    var student_id = this.data.userInfo.relative_jgs.student_jg?.student
    if(student_id){
      var question_id = this.data.ti_list[this.data.current_list_index].id
      var ti_bookmarks = this.data.ti_bookmarks
      bookmark_set.add_or_delete(this, question_id, student_id, ti_bookmarks)
    }else{
      wx.showToast({
        title: '仅学员可用！',
        duration: 1500,
        icon: 'success',
      })
    }
  },
  // 点击选题
  sel(e){app.get_vibration();sel(this,e)},

  // 初始化加载题
  page_init(){
    wx.showLoading({
      title: '连接题库中……',
      mask: true,
    })
    load_questions(this)
    load_bookmarks(this)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.test_paper_info = JSON.parse(decodeURIComponent(options.test_paper_info))
    this.page_init()
    this.setData({
      windowHeight : wx.getWindowInfo().windowHeight,
      userInfo:app.globalData.userInfo,
    })
  },

  onUnload(){
    // 清楚定时器
    clearInterval(this.data.timer_id)
    // console.log('清楚定时器')
  },


})